package ${commonPackageName}.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.codec.Base64;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * excel导出导入封装
 * @author lizihao
 *
 */
public class ExcelClient<T> {

	/**
	 * 上传的excel转对象集合
	 * @param uploadFile 前端上传的文件
	 * @param headAlias  表头对应字段
	 * @param beanClass  对象类型
	 * @return
	 * @throws IOException
	 */
	public static <T>List<T> excelToList(MultipartFile uploadFile,Map<String, String> headAlias,Class<T> beanClass) throws IOException{
		ExcelReader reader = ExcelUtil.getReader(uploadFile.getInputStream());
		reader.setHeaderAlias(headAlias);
		return reader.readAll(beanClass);
	}
	
	/**
	 * 对象集合转excel(base64字符串)
     * @param headAlias  表头对应字段
	 * @param list  传入的对象集合
	 * @return
	 */
	public static String listToExcel(List<?> list,Map<String, String> headAlias) {
		ExcelWriter writer = ExcelUtil.getWriter();
        writer.setHeaderAlias(headAlias);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list,true);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        writer.flush(stream);
        // 关闭writer，释放内存
        writer.close();
        return Base64.encode(stream.toByteArray());
	}
	
}
